//
//  StatusRetweetedView.swift
//  新浪微博
//
//  Created by 赵春浩 on 15/12/21.
//  Copyright © 2015年 DreamFlyingCow. All rights reserved.
//

import UIKit
import SnapKit

// 转发微博, 转发微博正文 + 配图视图
class StatusRetweetedView: UIView {

    // 定义约束属性, 保存当前视图的底部约束
    var bottomContraints: Constraint?
    // MARK: 定义外部属性模型
    var retweetedStatus: Status? {
        didSet {
            retweetedLabel.text = "@" + (retweetedStatus?.user?.name ?? "") + (retweetedStatus?.text ?? "")
            pictureView.imageURLs = retweetedStatus?.imageURLs
            
            // 记得先卸掉底部约束
            self.bottomContraints?.uninstall()
            // 根据是否有配图视图, 重新添加约束
            if let urls = retweetedStatus?.imageURLs where urls.count > 0 {
                // 这里说明有配图
                self.snp_makeConstraints(closure: { (make) -> Void in
                    // 1. 添加约束
                    // 记录底部约束
                    self.bottomContraints = make.bottom.equalTo(pictureView.snp_bottom).offset(StatusCellMargin).constraint
                })
            } else {
                // 没有配图
                self.snp_makeConstraints(closure: { (make) -> Void in
                    self.bottomContraints = make.bottom.equalTo(retweetedLabel.snp_bottom).offset(StatusCellMargin).constraint
                })
                
                
            }
        }
    }
    
    // MARK: 重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        backgroundColor = UIColor(white: 0.95, alpha: 1)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: 设置页面和布局
    private func setupUI() {
        
        addSubview(retweetedLabel)
        addSubview(pictureView)
        
        // 添加约束
        retweetedLabel.snp_makeConstraints { (make) -> Void in
            make.left.top.equalTo(self).offset(StatusCellMargin)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(retweetedLabel.snp_bottom).offset(StatusCellMargin)
            make.left.equalTo(retweetedLabel.snp_left)
        }
        
        
        // 转发微博自动计算行高
        self.snp_makeConstraints { (make) -> Void in
            self.bottomContraints = make.bottom.equalTo(pictureView.snp_bottom).offset(StatusCellMargin).constraint
        }
        
    }
    
    // MARK: 懒加载所有的子视图
    private lazy var retweetedLabel: UILabel = UILabel(title: "转发微博", color:  UIColor.darkGrayColor(), fontSize: 14, margin: StatusCellMargin)
    // 配图视图
    private lazy var pictureView: StatusCellPictureView = StatusCellPictureView()
    
}
